<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> -->
</head>
<body>
  <button onclick="testGet()">GET请求</button>
  <button onclick="testPost()">POST请求</button>
  <button onclick="testPut()">PUT请求</button>
  <button onclick="testDelete()">DELETE请求</button>

  <script>
    function axios({
      url,
      method="GET",
      params={},
      data={}
    }){
      return new Promise((resovle , reject)=>{
        // 处理method参数
        method = method.toUpperCase()

        // 处理query参数
        let queryStr = Object.keys(params).reduce((prev , current)=>{
          return `${prev}${current}=${params[current]}&`
        },'')
        if(queryStr){
          queryStr = queryStr.slice(0,-1)
          url += '?'+queryStr
        }

        // 执行异步ajax请求
        const xhr = new XMLHttpRequest()

        xhr.open(method, url)

        if(method === 'GET' || method === 'DELETE'){
          xhr.send()
        }else if(method === 'POST' || method ==='PUT'){
          xhr.setRequestHeader('Content-Type','application/json;charset=utf-8')
          xhr.send(JSON.stringify(data))
        }

        xhr.onreadystatechange= ()=>{
          if(xhr.readyState !==4){
            return
          }

          const { status , statusText } = xhr

          if(status>=200 && status<=299){
            const response ={
              data: JSON.parse(xhr.response),
              status,
              statusText
            }
            resovle(response) // 如果成功，调用resolve
          }else{
            reject(new Error('request error status is '+ status)) // 如果失败，调用reject
          }
        }  
      })
    }

    function testGet(){
      axios({
        url:'http://localhost:3000/posts',
        params:{
          id:1,
          xxx:'yyy'
        }
      }).then(res => {
        console.log(res);
      }).catch(err =>{
        console.log(err);
      })
    }

    function testPost(){
      axios({
        url:'http://localhost:3000/posts',
        method:'POST',
        data:{
          id:5,
          title:"hello",
          author:"welcome",
        }
      }).then(res => {
        console.log(res);
      }).catch(err =>{
        console.log(err);
      })
    }

    function testPut(){
      axios({
        url:'http://localhost:3000/posts/2',
        method:'put',
        data:{
          title:'test-put'
        }
      }).then(res => {
        console.log(res);
      }).catch(err =>{
        console.log(err);
      })
    }

    function testDelete(){
      axios({
        url:'http://localhost:3000/posts/2',
        method:'delete',
      }).then(res => {
        console.log(res);
      }).catch(err =>{
        console.log(err);
      })
    }

  </script>
</body>
</html>